<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="商品名称">
          <el-input
            v-model="queryParams.packageName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <template #icon><Plus /></template>
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="商品ID" prop="id" min-width="80" align="center" />
        <el-table-column key="packageName" label="商品名称" prop="packageName" min-width="150" align="center" />
        <el-table-column key="picUrl" label="图片" prop="picUrl" min-width="100" align="center">
          <template #default="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" alt="商品图片" style="width: 60px; height: 60px; object-fit: cover;" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column key="personCount" label="可修缮人数" prop="personCount" min-width="120" align="center" />
        <el-table-column key="price" label="价格" prop="price" min-width="100" align="center">
          <template #default="scope">
            {{ scope.row.price ? `¥${scope.row.price}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column key="totalQuota" label="总库存" prop="totalQuota" min-width="120" align="center" />
        <el-table-column key="availableQuota" label="可用库存" prop="availableQuota" min-width="120" align="center" />
        <el-table-column key="usedQuota" label="已使用" prop="usedQuota" min-width="120" align="center" />
        <el-table-column key="status" label="状态" prop="status" min-width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
            <el-tag v-else type="info">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="create_time" label="创建时间" prop="create_time" min-width="160" align="center" />
        <el-table-column key="update_time" label="更新时间" prop="update_time" min-width="160" align="center" />
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" size="small" link @click="handleAddQuota(scope.row)">增加库存</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑商品' : '新增商品'" width="500px">
      <el-form :model="editForm" label-width="120px" :rules="rules" ref="editFormRef">
        <el-form-item label="商品名称" prop="packageName">
          <el-input v-model="editForm.packageName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="图片" prop="picUrl">
          <SingleImageUpload v-model="editForm.picUrl" />
        </el-form-item>
        <el-form-item label="可修缮人数" prop="personCount">
          <el-input-number disabled v-model="editForm.personCount" :min="1" :precision="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="editForm.price" :min="0" :precision="2" :step="0.01" style="width: 100%">
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="平台库存" prop="totalQuota">
          <el-input-number disabled v-model="editForm.totalQuota" :min="1" :precision="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="300px">
      <span>确定要删除该商品吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitDelete">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="addQuotaDialogVisible" title="增加库存" width="400px">
      <el-form :model="addQuotaForm" label-width="100px" :rules="addQuotaRules" ref="addQuotaFormRef">
        <el-form-item label="增加数量" prop="quota">
          <el-input-number v-model="addQuotaForm.quota" :min="1" :precision="0" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addQuotaDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddQuota">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import PackageAPI from "@/api/genealogy/package.api";
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";

const queryFormRef = ref();
const editFormRef = ref();
const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  packageName: '',
  status: undefined,
});

const pageData = ref([]);

const editDialogVisible = ref(false);
const editForm = reactive({
  id: undefined,
  packageName: '',
  personCount: 1,
  price: 0,
  status: 1, // 1-启用，0-禁用
  picUrl: '', // 新增
  totalQuota:1,
});

const rules = {
  packageName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  picUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  personCount: [{ required: true, message: '请输入可修缮人数', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

const deleteDialogVisible = ref(false);
const currentDeleteId = ref<number>();

const addQuotaDialogVisible = ref(false);
const addQuotaFormRef = ref();
const addQuotaForm = reactive({
  id: undefined, // 商品ID
  quota: 1,      // 增加的库存数量
});
const addQuotaRules = {
  quota: [{ required: true, message: '请输入增加的库存数量', trigger: 'blur' }],
};

function handleQuery() {
  loading.value = true;
  PackageAPI.getPage(queryParams)
    .then((data: any) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

function handleEdit(row: any) {
  //Object.assign(editForm, row);
  editForm.id =row.id;
  editForm.packageName=row.packageName;
  editForm.price=row.price;
  editForm.status=row.status;
  editForm.personCount=row.personCount;
  editForm.picUrl=row.picUrl;
  editForm.totalQuota=row.totalQuota;
  editDialogVisible.value = true;
}

function handleAdd() {
  Object.assign(editForm, {
    id: undefined,
    packageName: '',
    personCount: 1,
    price: 0,
    status: 1,
    picUrl: '',
    totalQuota:1,
  });
  editDialogVisible.value = true;
}

function handleDelete(row: any) {
  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
}

function handleAddQuota(row: any) {
  addQuotaForm.id = row.id;
  addQuotaForm.quota = 1;
  addQuotaDialogVisible.value = true;
}

function submitEdit() {
  editFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    const api = editForm.id ?
      PackageAPI.edit(editForm.id, editForm) :
      PackageAPI.add(editForm);
    api.then(() => {
      ElMessage.success(editForm.id ? '编辑成功' : '新增成功');
      editDialogVisible.value = false;
      handleQuery();
    })
      .catch(() => {
        ElMessage.error(editForm.id ? '编辑失败' : '新增失败');
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function submitDelete() {
  if (!currentDeleteId.value) return;
  loading.value = true;
  PackageAPI.delete(currentDeleteId.value)
    .then(() => {
      ElMessage.success('删除成功');
      deleteDialogVisible.value = false;
      handleQuery();
    })
    .catch(() => {
      ElMessage.error('删除失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

function submitAddQuota() {
  addQuotaFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    // 假设 PackageAPI.addQuota(id, { quota }) 是后端接口
    PackageAPI.addQuota(addQuotaForm.id, { quota: addQuotaForm.quota })
      .then(() => {
        ElMessage.success('增加库存成功');
        addQuotaDialogVisible.value = false;
        handleQuery();
      })
      .catch(() => {
        ElMessage.error('增加库存失败');
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
